<?php
namespace Partner\Controller;

use Utuo\BackgroundController;

class PartnerMenuManagerController extends BackgroundController {

	private $reqAid = 0;
	
	public function _initialize() {
		$this->reqAid = I('aid', 0, 'intval'); // 合作商管理员id
		$this->setControllerTitle("合作商管理员菜单管理");
		$this->setActionTitle(array(
			'index'=>'合作商管理员菜单管理',
		),'','aid='.$this->reqAid);
		$this->setActionNav("index");
	}
	
	public function indexAction() {
		$aid = I('aid', 0, 'intval'); // 合作商管理员id
		$condition = array(
				'aid' => $aid );
		$partnerMenuManagerSql = M("PartnerMenuManager")->where($condition)->field("id,menu_id")->select(false);
		//$partnerMenuLists = M()->query("select a.*,b.id>0 is_selected from ".C("DB_PREFIX")."partner_menu"." a LEFT JOIN $partnerMenuManagerSql b on a.id=b.menu_id where a.is_deleted=0");
		$partnerMenuLists = M()->query("select a.*,b.id>0 is_selected from ".C("DB_PREFIX")."partner_menu_assign c left join ".C("DB_PREFIX")."partner_menu"." a on c.menu_id=a.id LEFT JOIN $partnerMenuManagerSql b on a.id=b.menu_id where a.is_deleted=0 and c.pid={$this->aid}");
		$menuTree = $this->getTree($partnerMenuLists, 0);
		$menuListHtml = $this->procHtml( $menuTree );
		$this->assign("aid", $aid);
		$this->assign("menuListHtml", $menuListHtml);
		$this->display();
	}
	
	public function saveAction() {
		$aid = I('aid', 0, "intval");
		$nodes = I("node", 0) or $this->ajaxError("没有选择任何菜单");
		$condition = array('aid' => $aid, );
	    $m = M("PartnerMenuManager");
		$currentNodes = $m->where($condition)->getField("id,menu_id") or $currentNodes = array(); // 已有菜单项
	    $m->where(array( 'aid' => $aid, 'menu_id' => array('not in', $nodes)))->delete(); // 删除菜单项
		$newNodes = array_diff($nodes, $currentNodes); // 新增菜单项
		if( $newNodes ) {
			foreach ($newNodes as $v) {
				false == $m->add(array(
					'aid' => $aid,
					'menu_id' => $v,
				)) and $this->ajaxError("保存失败!");
			}
		}
		$this->ajaxSuccess("保存成功!");
	}

	private function procHtml( $tree ) {
		$html = '';
		foreach($tree as $t) {
			if($t['pid'] == '') {
				$html .= "<li class=\"".(!$t['level']?"root_li":"")."\"><label><input name=\"node[{$t['id']}]\" value=\"{$t['id']}\" ".($t['is_selected']?'checked=checked':'')." type=\"checkbox\">&nbsp;{$t['name']}</label></li>";
			} else {
				$html .= "<li class=\"parent_menu_title ".(!$t['level']?"root_li":"")."\"><label class=\"parent_title\"><input name=\"node[{$t['id']}]\" value=\"{$t['id']}\" ".($t['is_selected']?'checked=checked':'')." type=\"checkbox\">&nbsp;{$t['name']}</label>";
				$html .= $this->procHtml( $t['pid'] );
				$html = $html."</li>";
			}
		}
		return $html ? '<ul>'.$html.'</ul>' : $html ;
	}
	
	private function getTree($data, $pId, $level=0) {
		$tree = '';
		foreach($data as $k => $v) {
			if($v['pid'] == $pId) {
				$v['level'] = $level;
				unset($data[$k]);
				$v['pid'] = $this->getTree($data, $v['id'], $level+1);
				$tree[] = $v;
			}
		}
		return $tree;
	}
	
}